﻿//authority是权限列表，从数据库读出，在head.js中定义
if ((authority[2] | authority[3] | authority[4]) === 0) {//没有权限时自动返回主页
    alert("你没有权限查看此内容");
    window.location.href = "index.html";
}
var projectName = []; //新建委托单时选择的项目，详见44行
var projectOption = document.getElementById("projectOption");//获取projectOption元素，用于新建委托单时选择项目
var rawData = [[], [], []];//原始数据，进行搜索操作时，先读取该数据，然后赋值给dummyData进行显示。


var taskMessage;
var projectMessage;
//12-36行初始化向后端发送的数据


if (authority[18] === 1){//超级管理员
    taskMessage = {
        "requestType": "superManager"
    };
}else {
    if (authority[2] === 1) {//检测主管
        taskMessage = {
            "requestType": "manager",
            "user_part": user.staff_part
        };
    }
    else if (authority[3] === 1) {//客户查看自己的
        taskMessage = {
            "requestType": "client",
            "task_uid": user.user_id
        };
        projectMessage = {
            "requestType": 'client',
            "pj_client": user.user_id
        };
    }
    else if (authority[4] === 1) {//业务部门
        taskMessage = {
            "requestType": "staff"
        };
        projectMessage = {
            "requestType": 'staff'
        };
    }
}
//载入所有项目名称，然后加入新建委托单的选项中
if (authority[3] | authority[4] === 1) {
    //向后端发送请求
    $.ajax({
        url: '/pj/project_list',
        type: 'post',
        data: projectMessage,
        async: false,
        success: function (data, status) {
            if (status == 'success') {
                for (let i = 0; i < data.length; i++) {
                    projectName.push([data[i].pj_name, data[i].pj_id]);
                }
            }
        },
        error: function (data, status) {
            if (status == 'error') {
                alert("你的网络有问题！");
            }
        }
    });
    //循环，先创建option元素，然后加进projectOption元素里面
    for (let i = 0; i < projectName.length; i++) {
        let option = document.createElement("option");
        option.innerHTML = projectName[i][0];
        projectOption.appendChild(option);
    }
}
var postData;
$.ajax({
    url: '/task/task_list',
    data: taskMessage,
    type: 'post',
    async: false,
    success: function (data, status) {
        if (status == 'success') {
            postData = data;
            console.log(postData);
        }

    },
    error: function (data, status) {
        if (status == 'error') {
            alert("你的网络有问题！");
        }
    }
});
// console.log(authority)
//向rawData中存入数据。
if (authority[2] === 1) {//检测主管查看委托单和分配工艺卡/检测小组
    for (let i = 0; i < postData.length; i++) {
        let temp = [
            postData[i].task_id,
            postData[i].task_type,
            postData[i].task_workNum,
            postData[i].task_pname,
            postData[i].task_company,
            postData[i].user_name,
            postData[i].task_passTech + "/" + postData[i].task_tech,
            postData[i].task_passTeam + "/" + postData[i].task_team,
            postData[i].part_name
        ];
        //rawData[0]:未处理完   rawData[1]:已处理完     rawData[2]:全部
        rawData[2].push(temp);
        postData[i].task_passTeam == postData[i].task_team ? rawData[1].push(temp) : rawData[0].push(temp)
        // switch (postData[i].task_state) {
        //     case 0: {
        //         rawData[0].push(temp);
        //         break;
        //     }
        //     case 1:
        //     case 2: {
        //         rawData[1].push(temp);
        //     }
        // }
    }
}
else if (authority[3] === 1) {//客户查看、新建（自己的）委托单
    for (let i = 0; i < postData.length; i++) {
        //let state;
        //switch (postData[i].task_state) {//显示工艺卡的状态
        //    case 0: {
        //        state = "进行中";
        //        break;
        //    }
        //    case 1: {
        //        state = "已结束";
        //        break;
        //    }
        //}
        if(postData[i].task_start!=null){
        var date1 = new Date(postData[i].task_start);
        postData[i].task_start = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
        date1.getDate();}
        if(postData[i].task_fin!=null){
        var date2 = new Date(postData[i].task_fin);
        postData[i].task_fin = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
        date2.getDate();}
        let temp = [
            postData[i].task_id,
            postData[i].task_type,
            postData[i].task_pname,
            postData[i].task_state === 0 ? "进行中" : "已结束",
            postData[i].task_workNum,
            postData[i].task_start,
            postData[i].task_fin == null ? "&nbsp&nbsp&nbsp&nbsp- " : postData[i].task_fin
        ];
        rawData[2].push(temp);
        switch (postData[i].task_state) {
            case 0: {
                rawData[0].push(temp);
                break;
            }
            case 1:
            case 2: {
                rawData[1].push(temp);
            }
        }
    }
}
else if (authority[4] === 1) {//业务部门新建、查看委托单和委托人
    for (let i = 0; i < postData.length; i++) {
        let state;
        if(postData[i].task_start!=null){
        var date1 = new Date(postData[i].task_start);
        postData[i].task_start = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
        date1.getDate();}
        if(postData[i].task_fin!=null){
        var date2 = new Date(postData[i].task_fin);
        postData[i].task_fin = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
        date2.getDate();}
        let temp = [
            postData[i].task_id,
            postData[i].task_type,
            postData[i].task_pname,
            postData[i].task_state=== 0 ? "进行中" : "已结束",
            postData[i].task_workNum,
            postData[i].task_start == null ? "" : postData[i].task_start,
            postData[i].task_fin == null ? "&nbsp&nbsp&nbsp&nbsp-" : postData[i].task_fin,
            postData[i].task_company,
            postData[i].user_name,
            postData[i].part_name == null ? '&nbsp&nbsp&nbsp&nbsp-' : postData[i].part_name
        ];
        rawData[2].push(temp);
        if (authority[12] == 1){
            postData[i].task_state == 0 ? rawData[0].push(temp) : rawData[1].push(temp)
        }else {
            postData[i].part_name == null ? rawData[0].push(temp):rawData[1].push(temp)
            // if((postData[i].part_name) == null){
            //     rawData[0].push(temp);
            //     // break;
            // }else{
            //     rawData[1].push(temp);
            // }
        }
        for(let i = 0;i<2;i++){

        }
        /**
        switch (postData[i].task_state) {
            case 0: {
                rawData[0].push(temp);
                break;
            }
            case 1:
            case 2: {
                rawData[1].push(temp);
            }
        }*/
    }
}
var dummyData = [].concat(rawData); //复制rawData。dummyData是用于显示的、进行搜索筛选后的数据。



var title;
var methodCount;
var neededOptionIndex;
//显示选项卡
var optionCard = document.getElementById("optionCard"); //获取名为optionCard的元素。
//初始化表格标题，根据权限类型动态展示新建按钮和选项卡
if (authority[4] === 1) {//业务部门新建、查看自己的委托单
    optionCard.innerHTML = "<li class=\"active\"><a href=\"#lC\" data-toggle=\"tab\">全部</a></li>" + //html中没有定义li选项卡，这里根据不同权限显示不同选项卡
        "<li><a href=\"#lA\" data-toggle=\"tab\">进行中</a></li>" +
        "<li><a href=\"#lB\" data-toggle=\"tab\">已结束</a></li>";
    title = [//用于显示在表格标题栏的数据。
        ["编号", "委托单类型", "项目名称", "状态", "工件数量", "开始时间", "结束时间", "委托单位", "委托人", "检测部门", "详细信息"],
        ["编号", "委托单类型", "项目名称", "状态", "工件数量", "开始时间", "结束时间", "委托单位", "委托人", "检测部门", "详细信息"],
        ["编号", "委托单类型", "项目名称", "状态", "工件数量", "开始时间", "结束时间", "委托单位", "委托人", "检测部门", "详细信息"]];
    methodCount = [10, 10, 10]; //表格中数据的列数。加入这个变量是由于表格上会有按钮，数据的列数小于标题的列数
    neededOptionIndex = [
        [1, 2, 3, 7, 8, 9],
        [1, 2, 3, 7, 8, 9],
        [1, 2, 3, 7, 8, 9]
    ];
}
else if (authority[3] === 1) {//客户新建、查看自己的委托单
    optionCard.innerHTML = "<li class=\"active\"><a href=\"#lC\" data-toggle=\"tab\">全部</a></li>" +
        "<li><a href=\"#lA\" data-toggle=\"tab\">进行中</a></li>" +
        "<li><a href=\"#lB\" data-toggle=\"tab\">已结束</a></li>";
    title = [
        ["编号", "委托单类型", "项目名称", "状态", "工件数量", "开始时间", "结束时间", "详细信息"],
        ["编号", "委托单类型", "项目名称", "状态", "工件数量", "开始时间", "结束时间", "详细信息"],
        ["编号", "委托单类型", "项目名称", "状态", "工件数量", "开始时间", "结束时间", "详细信息"]];
    //下面这一行指的是把id为new的元素里面的HTML替换为指定内容。这里其实就是放了一个新建按钮，因为检测主管没有新建按钮，所以上面没有这一句。
    document.getElementById("new").innerHTML = "<button data-toggle=\"modal\" data-target=\"#chooseProject\" class=\"btn btn-xs btn-success\"><i class=\"ace-icon fa fa-plus bigger-120\"> 新建委托单</i></button>";
    methodCount = [7, 7, 7];//表格中数据的列数。加入这个变量是由于表格上会有按钮，数据的列数小于标题的列数
    neededOptionIndex = [
        [1, 2, 3, 4],
        [1, 2, 3, 4],
        [1, 2, 3, 4]
    ];
}
else if (authority[2] === 1) {//主管查看自己的委托单和委托人
    optionCard.innerHTML = "<li class=\"active\"><a href=\"#lC\" data-toggle=\"tab\">全部</a></li>" +
        "<li><a href=\"#lA\" data-toggle=\"tab\">未处理完</a></li>" +
        "<li><a href=\"#lB\" data-toggle=\"tab\">已处理完</a></li>";
    title = [
        ["编号", "委托单类型", "工件数量", "项目名称", "委托单位", "委托人", "工艺卡状态", "检测小组", "详细信息"],
        ["编号", "委托单类型", "工件数量", "项目名称", "委托单位", "委托人", "工艺卡状态", "检测小组", "详细信息"],
        ["编号", "委托单类型", "工件数量", "项目名称", "委托单位", "委托人", "工艺卡状态", "检测小组", "详细信息"]];
    //因为业务部门也没有新建委托单的权限，所以也不需要下面这条语句
    //document.getElementById("new").innerHTML = "<button data-toggle=\"modal\" data-target=\"#chooseProject\" class=\"btn btn-xs btn-success\"><i class=\"ace-icon fa fa-plus bigger-120\"> 新建委托单</i></button>";
    methodCount = [9, 9, 9];
    neededOptionIndex = [
        [1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]
    ];
}


var pageID = [1, 1, 1];//用于保存当前的页码。
//设置每一页的行数
var countPerPage=[];

//默认情况下
if(user.countPerPage== 0){
    countPerPage = [10, 10, 10];
    $('.rowNum').val(10)
}else {
    countPerPage = [user.countPerPage,user.countPerPage,user.countPerPage];
    $('.rowNum').val(user.countPerPage)
}

//点击设置每一页行数的确定按钮
$('.rowsBut').click(function () {
    //获得文本框中输入的值
    var rowsNumbuer = $('.rowNum').val();
    //将该值传入到后台中
    $.ajax({
        url:'/pj/countPerPage',
        type:'post',
        data:{'rowsNumbuer': rowsNumbuer},
        async:false,
        success:function () {
            //console.log('点击确认以后的countPerPage'+user.userId)
            if(user.countPerPage== 0){
                countPerPage = [10, 10, 10];
                $('.rowNum').val(10)
            }else {
                countPerPage = [user.countPerPage,user.countPerPage,user.countPerPage];
                $('.rowNum').val(user.countPerPage)
            }
        },
        error:function () {
            if (status == 'error') {
                alert("你的网络有问题！");
            }
        }
    });
    //刷新页面
    location.reload()
})
var pageButtonCount = [8, 8, 8];//定义每页中表格翻页按钮的最大数量（超过这个数时，其他的页码会隐藏），可以根据需要修改
var pageCount = [parseInt((dummyData[0].length - 1) / countPerPage[0]) + 1,
parseInt((dummyData[1].length - 1) / countPerPage[1]) + 1,
parseInt((dummyData[2].length - 1) / countPerPage[2]) + 1];//计算页数
var table = [document.getElementById("table0"), document.getElementById("table1"), document.getElementById("table2")];//获取表格元素
var tbody = [table[0].children[1], table[1].children[1], table[2].children[1]];
var pages = [document.getElementById("pages0"), document.getElementById("pages1"), document.getElementById("pages2")];
console.log(tbody[0].innerHTML);
//初始化搜索栏可选项。此处应另开一个数组，读取该数组中的数据，而不是title中的数据
for (let i = 0; i < neededOptionIndex.length; i++) {
    for (let j = 0; j < neededOptionIndex[i].length; j++) {
        let option = document.createElement("option");
        option.innerHTML = title[i][neededOptionIndex[i][j]];
        document.getElementById("searcher" + i).children[1].appendChild(option);
    }
}
//for (let i = 0; i < methodCount.length; i++) {
//    for (let j = 0; j < methodCount[i]; j++) {
//        let option = document.createElement("option");
//        option.innerHTML = title[i][j];
//        document.getElementById("searcher" + i).children[1].appendChild(option);
//    }
//}
//初始化表格，添加一定的行数和列数
for (let i = 0; i < methodCount.length; i++) {
    let inner = "<td>&nbsp;</td>";
    for (let j = 0; j < title[i].length - 1; j++) {
        inner += "<td />";
    }
    for (let j = 0; j < countPerPage[i]; j++) {
        var tr = document.createElement("tr");
        tr.innerHTML = inner;
        tbody[i].appendChild(tr);
    }
}
for (let i = 0; i < methodCount.length; i++) {
    //生成翻页按钮
    for (let j = 0; j < (pageCount[i] > pageButtonCount[i] ? pageButtonCount[i] : pageCount[i]); j++) {
        var li = document.createElement("li");
        li.setAttribute("onclick", "OnClick(" + (j + 1) + ", " + i + ")");
        var a = document.createElement("a");
        a.innerHTML = j + 1;
        a.setAttribute("href", "#");
        li.appendChild(a);
        pages[i].insertBefore(li, pages[i].lastElementChild);
    }
    //装填标题栏
    for (let j = 0; j < title[i].length; j++) {
        let t = document.createElement("th");
        t.innerHTML = title[i][j];
        table[i].children[0].children[0].appendChild(t);
    }
    //（重点）调用该函数即显示第一页内容。详见OnClick的定义
    OnClick(1, i);
}

// 注意：这一段代码移动时要放在select对象中option创建之后，否则selectedIndex为-1
var paraBegin = location.href.indexOf("?");//第一个？ 用来传递网页间参数
var paraStr;
if (paraBegin !== -1) {
    paraStr = location.href.substr(paraBegin + 1);// 获取“?”后面的参数

    let searcher = document.getElementById("searcher2");//搜索栏对象
    if (authority[4] === 1 || authority[3] === 1) {
        searcher.children[1].selectedIndex = 1;//“项目名”在下拉列表中位置
    }
    else if (authority[2] === 1) {
        searcher.children[1].selectedIndex = 2;//“项目名”在下拉列表中位置
    }
    console.log();//DDF
    searcher.children[3].value = decodeURI(paraStr);//检索的内容 uri解码
    OnSearch(2);//“全部”界面，筛选一次
}


function OnClick(index, cardIndex) {//显示第index页，cardIndex为选项卡的编号。搜索时也用这个函数刷新表格
    if (index === -1) {//-1和-2分别代表向上、向下翻页
        if (pageID[cardIndex] > 1) OnClick(pageID[cardIndex] - 1, cardIndex);
        return;
    }
    if (index === -2) {
        // console.log("b" + pageID);
        if (pageID[cardIndex] < pageCount[cardIndex]) OnClick(pageID[cardIndex] + 1, cardIndex);
        return;
    }
    if (index === 1 && dummyData[cardIndex].length < countPerPage[cardIndex]) {//如果不到一页，则不显示翻页按钮，并且隐藏空行
        for (let i = 0; i < dummyData[cardIndex].length; i++) {
            tbody[cardIndex].children[i].setAttribute("style", "");
        }
        for (let i = dummyData[cardIndex].length; i < countPerPage[cardIndex]; i++) {
            tbody[cardIndex].children[i].setAttribute("style", "display: none");
        }
        pages[cardIndex].setAttribute("style", "display: none");
    }
    else {
        for (let i = 0; i < countPerPage[cardIndex]; i++) {//否则，显示所有行和翻页按钮
            tbody[cardIndex].children[i].setAttribute("style", "");
        }
        pages[cardIndex].setAttribute("style", "");
    }
    pageID[cardIndex] = index;//更新当前的页码
    //装填数据
    for (let i = 0; i < countPerPage[cardIndex]; i++) {//dummyData的第一个下标是选项卡编号，第二个下标每个即一行数据
        //dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i]可以定位到当前装填的数据
        if (dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i] !== undefined) {
            /**
             * 需要先判断检测部门的状态是否为空，
             *      如果为空：则放入进行中列表中，
             *      如果不为空则放入已结束、全部的列表中
             */
            for (let j = 0; j < methodCount[cardIndex]; j++) {
                //把数据放进表格
                tbody[cardIndex].children[i].children[j].innerHTML = dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i][j];
                //那个选项卡的，哪一行数据。装填进去
            }
            //根据不同的权限显示操作按钮
            if (authority[4] === 1) {//业务查看、新建委托单
                //创建button元素。此时它还没被放进HTML文档中
                let button = document.createElement("a");
                let hasDepartment = dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i][9] == '&nbsp&nbsp&nbsp&nbsp-' ? false : true;
                //setAttribute是原生js中设置属性的方法。
                button.setAttribute("href", "javascript:void(0)");
                //设置点击事件，跳转到viewDepute.html页面。?后面是url参数
                //审核人员没有分配功能
                if (authority[12] == 1){
                    button.setAttribute("onclick", "window.location.href='/viewDepute.html?id="
                        + dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i][0] + "&h=true" + "'");
                }else {
                    button.setAttribute("onclick", "window.location.href='/viewDepute.html?id="
                        + dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i][0] + "&h=" + hasDepartment + "'");//pao
                }
                button.innerHTML = "查看";
                //把按钮放进表格。innerHTML和outerHTML分别表示内部HTML代码和自身HTML代码。
                //tbody[cardIndex].children[i].children[title[cardIndex].length - 1]可以定位到当前操作的表格最后一格。以此类推，-2就是倒数第二格
                tbody[cardIndex].children[i].children[title[cardIndex].length - 1].innerHTML = button.outerHTML;
            }
            else if (authority[3] === 1) {//客户查看委托单
                button = document.createElement("a");
                button.setAttribute("href", "javascript:void(0)");
                button.setAttribute("onclick", "window.location.href='/viewDepute.html?id="
                    + dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i][0] + "'");//pao
                button.innerHTML = "查看";
                tbody[cardIndex].children[i].children[title[cardIndex].length - 1].innerHTML = button.outerHTML;
            }
            else if (authority[2] === 1) {//主管查看委托单
                button = document.createElement("a");
                button.setAttribute("href", "javascript:void(0)");
                //注意这里跳转的地址不一样
                button.setAttribute("onclick", "window.location.href='/viewWorkpieceType.html?id="
                    + dummyData[cardIndex][(index - 1) * countPerPage[cardIndex] + i][0] + "'");
                button.innerHTML = "查看";
                tbody[cardIndex].children[i].children[title[cardIndex].length - 1].innerHTML = button.outerHTML;
            }
        } else {
            //遇到dummyData没有对应数据时，这一行变成空行。一般是最后一页会遇到这种情况
            tbody[cardIndex].children[i].children[0].innerHTML = "&nbsp;";
            for (let j = 1; j < title[cardIndex].length; j++) {
                tbody[cardIndex].children[i].children[j].innerHTML = "";
            }
        }
    }
    //刷新翻页按钮
    if (pageCount[cardIndex] > pageButtonCount[cardIndex]) {
        var first = parseInt(pageID[cardIndex] - pageButtonCount[cardIndex] / 2) + 1;
        if (first < 1) first = 1;
        if (first > pageCount[cardIndex] - pageButtonCount[cardIndex] + 1) first = pageCount[cardIndex] - pageButtonCount[cardIndex] + 1;
        for (let i = 0; i < pageButtonCount[cardIndex]; i++) {
            pages[cardIndex].removeChild(pages[cardIndex].children[1]);
        }
        for (let i = first; i < first + pageButtonCount[cardIndex]; i++) {
            var li = document.createElement("li");
            li.setAttribute("onclick", "OnClick(" + i + ", " + cardIndex + ")");
            if (i === pageID[cardIndex])
                li.setAttribute("class", "active");
            var a = document.createElement("a");
            a.innerHTML = i;
            a.setAttribute("href", "#");
            li.appendChild(a);
            pages[cardIndex].insertBefore(li, pages[cardIndex].lastElementChild);
        }
    } else {
        for (let i = 0; i < pageCount[cardIndex]; i++) {
            pages[cardIndex].removeChild(pages[cardIndex].children[1]);
        }
        for (let i = 0; i < pageCount[cardIndex]; i++) {
            li = document.createElement("li");
            li.setAttribute("onclick", "OnClick(" + (i + 1) + ", " + cardIndex + ")");
            if (i + 1 === pageID[cardIndex])
                li.setAttribute("class", "active");
            a = document.createElement("a");
            a.innerHTML = i + 1;
            a.setAttribute("href", "#");
            li.appendChild(a);
            pages[cardIndex].insertBefore(li, pages[cardIndex].lastElementChild);
        }
    }
    // console.log("d" + pageID);
}

function OnConfirmDepute() {//新建委托单-确定的点击事件
    window.location.href = "newDepute.html?id=" + projectName[projectOption.selectedIndex][1];
}

function OnSearch(cardIndex) {
    let searcher = document.getElementById("searcher" + cardIndex);//搜索栏对象
    let condition = searcher.children[1].selectedIndex;//下拉菜单中选择的那一项的下标
    let details = searcher.children[3].value;//检索的内容
    let timeRange = [searcher.children[5].value, searcher.children[7].value];//两个用来检索的时间，中间必定有一个逗号
    var handyData = rawData[cardIndex];//该页面上的信息
    var resultData = new Array();//存放检索结果
    for (let i = 0; i < handyData.length; i++) {
        //字符串匹配，长度为0则全匹配
        var regx = new RegExp(details);
        //if (regx.exec(handyData[i][condition])) {
        if (regx.exec(handyData[i][neededOptionIndex[cardIndex][condition]])) {
            if (authority[3] === 1 || authority[4] === 1) {
                if (searcher.children[5].value.length !== 0 && searcher.children[5].value > handyData[i][5])//“开始时间”
                    continue;
                if (searcher.children[7].value.length !== 0 && searcher.children[7].value < handyData[i][5])//“结束时间”
                    continue;
            }
            resultData.push(handyData[i]);//加入符合的项
        }
    }
    dummyData[cardIndex] = resultData;//替换，反正再返回当前页面会变回来

    OnClick(1, cardIndex);
}